package com.yubest.shiro.service.shiro;

import cn.hutool.core.util.StrUtil;
import com.yubest.shiro.consts.Consts;
import org.apache.shiro.web.servlet.ShiroHttpServletRequest;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.apache.shiro.web.util.WebUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.Serializable;

/**
 * session管理器
 *
 * @Author: hweiyu
 * @Date: 2022/11/7 15:37
 */
public class MySessionManager extends DefaultWebSessionManager {

    private static final String REFERENCED_SESSION_ID_SOURCE = "Stateless request";

    /**
     * token标识，先从header中取，取不到再从request params中取
     * @param request
     * @param response
     * @return
     */
    @Override
    protected Serializable getSessionId(ServletRequest request, ServletResponse response) {
        String token = WebUtils.toHttp(request).getHeader(Consts.TOKEN_KEY);
        if (StrUtil.isBlank(token)) {
            token = WebUtils.toHttp(request).getParameter(Consts.TOKEN_KEY);
        }
        if (StrUtil.isNotBlank(token)) {
            request.setAttribute(REFERENCED_SESSION_ID_SOURCE, REFERENCED_SESSION_ID_SOURCE);
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID, token);
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_IS_VALID, Boolean.TRUE);
        }
        return token;
    }
}
